package com.cindata

import grails.transaction.Transactional

@Transactional
class CollateralFlowStageService
{
    def initFlowStage(Collateral collateral, Workflow workflow)
    {
        def executionSequence = CollateralFlowStage.findByCollateral(collateral, [sort: 'executionSequence', order: 'desc'])?.executionSequence
        def workflowStages = WorkflowStage.findAllByWorkflow(workflow)
        workflowStages?.each {
            def collateralFlowStage = new CollateralFlowStage()
            collateralFlowStage.executionSequence = executionSequence ? (executionSequence + it?.executionSequence) : it?.executionSequence
            collateralFlowStage.stage = it?.stage
            collateralFlowStage.canReject = it?.canReject
            collateralFlowStage.layout = it?.layout
            collateralFlowStage.collateral = collateral
            if (collateralFlowStage.validate())
            {
                collateralFlowStage.save flush: true
            }
            else
            {
                println collateralFlowStage.errors
            }
        }
    }
}
